import React  from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Tag, Input, Popover, Radio, Button } from 'antd'
const Search = Input.Search;
import constants from 'share/constants'
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service'
import debounce from 'lodash.debounce'
import moment from 'moment'
import 'styles/corporate-payment-report/index.scss'
import Stations from 'components/template/proxies/stations';
import {dealListTag, messages, queryCurrencyPrecision} from 'share/common';
import baseService from 'share/base.service';
import errorMessage from 'share/errorMessage';
import AdvancedTable from 'components/advanced-table'
import openSlideFrame from 'share/openSlideFrame'
import Space from "components/space";

class CorporatePaymentReport extends React.Component {

  statusRadio = [{
    label: messages('common.all')/*全部*/,
    value: '100110021003100410051006100710081015'
  }].concat(...constants.expenseStatus)
    .filter(i => i.value !== '10011004');

  constructor(props){
    super(props);
    constants.documentStatus.map(status => status.label = status.text);
    this.state = {
      searchForm: [{
        id: 'formOID', label: messages('common.document.name'), component: 'Selector',
        props: {
          type: 'proxyForm',
          params: { formType: 106, isAll: true }
        },
        dataIndex: 'formName'
      },{
        id: 'submittedDate', label: messages('common.submit.date')/*提交日期*/,
        component: 'DateRangePicker',
        initialValue: [moment().subtract(1, 'month'), moment()],
        parser: value => ({
          startDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
          endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
        }),
        dataIndex: 'submittedDate'
      }, {
        id: 'applicantOIDs', label: messages('common.applicant')/*申请人*/,
        component: 'Chooser',
        props: {
          type: 'user_condition',
          labelKey: 'fullName',
          valueKey: 'userOID',
          listExtraParams: {
            roleType: 'TENANT',
            setOfBooksId: props.company.setOfBooksId
          },
          dataIndex: 'applicantName'
        },
        parser: value => ({
          applicantOIDs: value ? value.map(item => item.userOID) : null
        }),
        JSONObjectFormatterParams: ['fullName', 'userOID']
      }, {
        id: 'corpSupplierId', label: messages('finance-9.key1')/*供应商*/,
        component: 'Chooser',
        props: {
          type: 'vendor_account',
          labelKey: 'venNickname',
          valueKey: 'id',
          listExtraParams: {
            companyOid: props.company.companyOID
          },
          dataIndex: 'corpSupplierId'
        },
        parser: value => ({
          corpSupplierId: value ? value.map(item => item.id) : null
        })
      }, {
        id: 'title', label: messages('finance-9.key2')/*事由*/,
        component: 'Input',
      }, {
        id: 'status', label: messages('common.column.status'),
        component: <Radio.Group>
          {
            this.statusRadio
              .filter(item => props.profile['finance.payment.cancel'] ? true : item.value !== '1015')
              .map(item => <Radio key={item.value} value={item.value}>{item.label}</Radio>)
          }
        </Radio.Group>,
        initialValue: '100110021003100410051006100710081015',
        row: true,
        tagParser: value => this.statusRadio.find(item => item.value === value).label,
        dataIndex: 'status'
      }],
      businessCode: ''
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  handleSearch = businessCode => {
    this.setState({ businessCode }, () => {
      this.advancedTableRef.getList(true, 1);
    })
  };

  handlePrint = (e, info) => {
    e.stopPropagation();
    baseService.printExpense(info.expenseReportOID)
      .then(res => {
        window.open(res.data.link, '_blank');
      })
      .catch((err) => {
        errorMessage(err.response);
      });
  };

  columns = [{
    title: messages('common.submit.date')/*提交日期*/, dataIndex: 'submittedDate',
    render: (value,record) => moment(record.lastSubmittedDate||record.createdDate ).format('YYYY-MM-DD'),
    width: 120
  }, {
    title: messages('common.applicant'), dataIndex: 'applicantName',
    width:'8%',
    render: value => <Popover content={value}>{value}</Popover>
  }, {
    title: messages('finance-9.key3')/*供应商名称*/, dataIndex: 'corpSupplierName',
    render: value => <Popover content={value}>{value}</Popover>
  }, {
    title: messages('common.document.name'), dataIndex: 'formName',
    render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
  }, {
    title: messages('finance-9.key2')/*事由*/, dataIndex: 'title',
    render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
  }, {
    title: messages('common.document.code'), dataIndex: 'businessCode',
    render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
  }, {
    title: messages('common.currency'), dataIndex: 'currencyCode', width: 72
  }, {
    title: messages('finance-9.key4')/*到票金额*/, dataIndex: 'totalAmount',  align: 'right',
    render: (value,item) => this.filterMoney(value,queryCurrencyPrecision(item.currencyCode)), width: '7%'
  }, {
    title: messages('finance-9.key5')/*支付金额*/, dataIndex: 'paymentTotalAmount', align: 'right',
    render: (value, item) => this.filterMoney(value, queryCurrencyPrecision(item.baseCurrencyCode)), width: '7%'
  }, {
    title: messages('common.column.status'), dataIndex: 'status', width: this.props.language.code === 'zh_cn' ? '8%' : '13%',
    render: (value, record) => constants.documentStatus.map(item => {
      if(
        (item.value === String(value) && record.rejectType === 1000) ||
        item.value === String(value * 10000 + record.rejectType)
      ) {
        return <Tag color={item.color} style={{ margin: 0 }}>{item.label}</Tag>
      }
    })
  }, {
    title: messages('common.operation')/*操作*/,
    width: 100,
    dataIndex: 'printView',
    render: (value, record) => value === 1 ?
      <a onClick={e => this.handlePrint(e, record)}>{messages('common.print')/*打印*/}</a> :
      null
  }];

  service = (page, pageSize, searchParams) => {
    const { businessCode } = this.state;
    let params = { ...searchParams, businessCode };
    return corporatePaymentReportService.getCorporatePaymentReportList(page, pageSize, params);
  };

  handleRowClick = record => {
    openSlideFrame.openCorporateReportDetail({
      expenseReportOID: record.expenseReportOID,
      entry: 'my'
    }, {
      noPadding: true,
      className: 'corporate-payment-report-detail',
      afterClose: this.afterClose
    }, this);
  };

  afterClose = value => typeof value === 'boolean' && value && this.advancedTableRef.getList(true);

  handleNewCorporatePaymentReport = (formOid, jobId, userOID) => {
    this.context.router.push(
      menuRoute.getRouteItem('new-corporate-payment-report').url
        .replace(':formId', formOid)
        .replace(':userOID', userOID)
        .replace(':applicantJobId', jobId)
    );
  };

  render(){
    const { searchForm } = this.state;
    return(
      <div className="corporate-payment-report full-height-page">
        <AdvancedTable
          index
          title={messages('finance-9.key6')/*对公支付单*/}
          columns={this.columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="expenseReportOID"
          expandedRowRender={dealListTag}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          waterMark={true}
          onRef={ref => this.advancedTableRef = ref}
          tableName='corporate-payment-report'
          expandAll
        >
          <div className={'table-header-buttons'} style={{position: 'relative'}}>
            <Space>
              <Stations formType="106" onOk={this.handleNewCorporatePaymentReport}/>
              <Search
                className="input-search input-search-left"
                placeholder={messages('finance-9.key7')/*请输入对公支付单号*/}
                onChange={(e) => this.handleSearch(e.target.value)}
              />
            </Space>
          </div>
        </AdvancedTable>
      </div>
    )
  }
}

CorporatePaymentReport.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    profile: state.login.profile,
    company: state.login.company
  }
}

export default connect(mapStateToProps)(CorporatePaymentReport)


